package Codage;

import java.awt.Point;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import Codage.Model.Code;
import Codage.Model.ICode;
import Codage.Model.IState;

public class GraphicBuilder {
	
	public static void GraphicsToXml(GraphicAutomat ga, String fileName) {
		File f = new File(fileName);
		PrintWriter out = null;
		try {
			if (!f.exists()) {
				f.createNewFile();
			}
			out = new PrintWriter(new FileWriter(f));
		} catch (IOException e) {
			e.printStackTrace();
		} 
		Set<IState> set = ga.getCode().getAllState();
		
		out.println("<graph>");
		
		for (IState s : set) {
			Point p = ga.getPoint(s);
			if (p != null) {
				out.println("    <state>");
				out.println("        <mot>" + s.getId() + "</mot>");
				if (s.isFinal()) {
					out.println("        <isFinal>true</isFinal>");
				}
				out.println("        <x>" + p.x + "</x>");
				out.println("        <y>" + p.y + "</y>");
				out.println("    </state>");
			}
		}
		
		out.println("</graph>");
		out.close();
	}
	
	public static GraphicAutomat getGraphFromXML(String fileName)  {
		try {		
			XMLReader saxReader = XMLReaderFactory.createXMLReader();
	
			GraphXmlParser fb = new GraphXmlParser();
			saxReader.setContentHandler(fb);
		
			saxReader.parse(new InputSource(new FileReader(new File(fileName))));
			
			Map<String, Point> map = fb.getMap();
			Set<String> set = fb.getSet();

			ICode code = new Code(set);
			code.makeSardinasPattersonGraph();
			
			Map<IState,Point> newMap = new HashMap<IState,Point>(); 
			for (IState s : code.getAllState()) {
				Point p = map.get(s.getId());
				if (p != null) {
					newMap.put(s, p);
				}
			}
			GraphicAutomat gr = new GraphicAutomat(code);
			gr.getModel().setStatesPositions(newMap);
			return gr;
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
